package xin.lms.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.common.date.DateUtils;
import xin.common.http.response.PageResponse;
import xin.common.http.response.PageWrapper;
import xin.common.utils.StringUtils;
import xin.core.jpa.JpaConstant;
import xin.lms.model.Event;
import xin.lms.repository.EventRepository;
import xin.lms.request.EventLogPageRequest;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 * Event Service
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2018/7/29 13:58
 */
@Service
@Transactional(readOnly = true)
public class EventService {

    @Autowired
    private EventRepository repository;

    @Transactional
    public Event save(Event optLog) {
        return repository.save(optLog);
    }

    public PageResponse findPageList(EventLogPageRequest request ){
        Sort sort = new Sort(Sort.Direction.DESC,"operateDate");
        Pageable pageable = new PageRequest(request.getPageNumber()-1,request.getPageSize(),sort);
        Specification<Event> specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(StringUtils.isNotBlank(request.getName())){
                predicates.add(criteriaBuilder.like(root.get("name"),
                        JpaConstant.WILDCARD + request.getName() + JpaConstant.WILDCARD));
            }
            if(StringUtils.isNotBlank(request.getOperatorName())){
                predicates.add(criteriaBuilder.like(root.get("operatorName"),
                        JpaConstant.WILDCARD + request.getOperatorName() + JpaConstant.WILDCARD));
            }
            if(StringUtils.isNotBlank(request.getOperateDate())){
                Date start = DateUtils.parseDate(request.getOperateDate() + " 00:00:00");
                Date end = DateUtils.addDays(start,1);
                predicates.add(criteriaBuilder.between(root.get("operateDate"),start,end));

            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return PageWrapper.wrap(repository.findAll(specification, pageable));
    }
}
